<template>
  <view class="container">
    <!-- 筛选栏 -->
    <view class="filter-bar">
      <view class="filter-item" :class="{active: sortType === 'default'}" @click="changeSort('default')">
        <text>综合</text>
      </view>
      <view class="filter-item" :class="{active: sortType === 'sales'}" @click="changeSort('sales')">
        <text>销量</text>
      </view>
      <view class="filter-item" @click="changeSort('price')">
        <view class="price-text">
          <text>价格</text>
          <view class="price-arrows">
            <text class="arrow" :class="{active: sortType === 'price-asc'}">↑</text>
            <text class="arrow" :class="{active: sortType === 'price-desc'}">↓</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-list">
      <view class="list-container" v-if="goodsList.length > 0">
        <view class="goods-item" v-for="(item, index) in goodsList" :key="index" @click="goToDetail(item)">
          <image 
            class="goods-image" 
            :src="item.mainPic || '/static/images/default-goods.png'" 
            mode="aspectFill"
            @error="handleImageError(index)"
          ></image>
          <view class="goods-info">
            <text class="goods-name">{{item.name}}</text>
            <view class="goods-price-box">
              <text class="price">¥{{item.price || '暂无价格'}}</text>
              <text class="sales">已售 {{item.sales || 0}}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-else-if="!loading">
        <text>暂无商品</text>
      </view>

      <!-- 加载更多 -->
      <uni-load-more :status="loadMoreStatus" v-if="goodsList.length > 0"></uni-load-more>
    </view>
  </view>
</template>

<script>
import { farmerApi } from '@/api'
import uniLoadMore from '@dcloudio/uni-ui/lib/uni-load-more/uni-load-more.vue'

export default {
  components: {
    uniLoadMore
  },
  data() {
    return {
      loading: false,
      goodsList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: '',
        sortField: '',
        sortOrder: ''
      },
      loadMoreStatus: 'more', // more-加载前 loading-加载中 noMore-没有更多
      hasMore: true,
      sortType: 'default' // default, sales, price-asc, price-desc
    }
  },
  onLoad(options) {
    // 获取分类ID和标题
    if (options.type) {
      this.queryParams.type = options.type
    }
    if (options.title) {
      uni.setNavigationBarTitle({
        title: options.title
      })
    }
    this.loadGoodsList()
  },
  // 下拉刷新
  async onPullDownRefresh() {
    this.resetList()
    await this.loadGoodsList()
    uni.stopPullDownRefresh()
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  methods: {
    // 重置列表
    resetList() {
      this.goodsList = []
      this.queryParams.pageNum = 1
      this.hasMore = true
      this.loadMoreStatus = 'more'
    },
    // 加载商品列表
    async loadGoodsList() {
      if (this.loading) return
      
      try {
        this.loading = true
        this.loadMoreStatus = 'loading'
        
        const res = await farmerApi.getGoodsListByCategoryId(this.queryParams)
        console.log('商品列表数据:', res)
        
        // 更新列表数据
        if (this.queryParams.pageNum === 1) {
          this.goodsList = res.rows || []
        } else {
          this.goodsList = [...this.goodsList, ...(res.rows || [])]
        }
        
        // 更新分页状态
        const total = res.total || 0
        const hasNextPage = this.goodsList.length < total
        this.hasMore = hasNextPage
        this.loadMoreStatus = this.hasMore ? 'more' : 'noMore'
        
      } catch (error) {
        console.error('获取商品列表失败:', error)
        uni.showToast({
          title: '获取商品列表失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    // 加载更多
    loadMore() {
      if (this.hasMore) {
        this.queryParams.pageNum++
        this.loadGoodsList()
      }
    },
    // 切换排序方式
    changeSort(type) {
      if (type === 'price') {
        // 价格排序特殊处理
        if (this.sortType === 'price-asc') {
          this.sortType = 'price-desc'
        } else {
          this.sortType = 'price-asc'
        }
      } else {
        this.sortType = type
      }
      this.loadGoodsList()
    },
    // 跳转到商品详情
    goToDetail(goods) {
      uni.navigateTo({
        url: `/pages/goods/detail/index?id=${goods.id}`
      })
    },
    // 处理图片加载错误
    handleImageError(index) {
      // 如果图片加载失败，设置为默认图片
      if (this.goodsList[index]) {
        this.goodsList[index].mainPic = '/static/images/default-goods.png'
      }
    }
  }
}
</script>

<style>
.container {
  min-height: 100vh;
  background: #f8f8f8;
}

.filter-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  height: 88rpx;
  background: #fff;
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #eee;
}

.filter-item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 28rpx;
  color: #666;
}

.filter-item.active {
  color: #07c160;
  font-weight: bold;
}

.price-text {
  display: flex;
  align-items: center;
}

.price-arrows {
  display: flex;
  flex-direction: column;
  margin-left: 4rpx;
}

.arrow {
  font-size: 20rpx;
  line-height: 1;
  color: #999;
}

.arrow.active {
  color: #07c160;
}

.goods-list {
  margin-top: 88rpx;
  padding: 20rpx;
}

.list-container {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.goods-item {
  width: calc(50% - 20rpx);
  margin: 10rpx;
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
}

.goods-image {
  width: 100%;
  height: 320rpx;
  background: #f5f5f5;
}

.goods-info {
  padding: 16rpx;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  height: 80rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.goods-price-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16rpx;
}

.price {
  font-size: 32rpx;
  color: #ff4d4f;
  font-weight: bold;
}

.sales {
  font-size: 24rpx;
  color: #999;
}

.empty-state {
  padding-top: 200rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}
</style> 